

//
//  EmoticonInputView.swift
//  自定义表情键盘
//
//  Created by YYY on 2017/9/5.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

class EmoticonInputView: UIView {

    fileprivate let cellId = "cellId"
    //九宫格
    @IBOutlet weak var collectView: UICollectionView!
    //底部工具栏
    @IBOutlet weak var toolbar: UIView!
    
    //选中表情cell的闭包回调（可选闭包）
    fileprivate var selectedEmoticonCellCallBack: ((_ emoticonModel: CPJEmoticonModel?)->())?
    
    //类方法
    class func emoticonView(selectedEmoticonCellCallBack: @escaping(_ emoticonModel: CPJEmoticonModel?)->()) -> EmoticonInputView
    {
        let nib = UINib(nibName: "EmoticonInputView", bundle: nil)
        let view = nib.instantiate(withOwner: nil, options: nil)[0] as! EmoticonInputView
        //记录闭包
        view.selectedEmoticonCellCallBack = selectedEmoticonCellCallBack
        return view
    }
    
    override func awakeFromNib() {
        
        //注册cell(原生)
        //collectView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
        //注册cell（用xib加载cell）
//        let nib = UINib(nibName: "EmoticonCollectionViewCell", bundle: nil)
//        collectView.register(nib, forCellWithReuseIdentifier: cellId)
        
        //纯代码注册cell
        collectView.register(EmoticonCollectionViewCell.self, forCellWithReuseIdentifier: cellId)
    }
}

extension EmoticonInputView: UICollectionViewDataSource
{
    //分组数量
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        
        print("EmotionManager.shared.emotionsGroupArray.count: \(EmotionManager.shared.emotionsGroupArray.count)")
        return EmotionManager.shared.emotionsGroupArray.count
    }
    
    //每个分组中的表情数量
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return EmotionManager.shared.emotionsGroupArray[section].numberOfPages
    }
    
    //创建cell
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        //创建cell
        let cell = collectView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! EmoticonCollectionViewCell
        cell.emoticonsArray = EmotionManager.shared.emotionsGroupArray[indexPath.section].emoticons(page: indexPath.item)
        //设置cell代理
        cell.delegate = self
        //cell.label.text = "\(indexPath.section) \(indexPath.item)"
        
        //返回cell
        return cell
    }
}

//实现cell的代理方法
extension EmoticonInputView: EmoticonCellSelectedDelegate
{
    func emoticonCellDidSelected(cell: EmoticonCollectionViewCell, emoticonModel: CPJEmoticonModel?) {
        
        //执行闭包，回调选中的表情
        selectedEmoticonCellCallBack?(emoticonModel)
    }
}
